Welcome to python!

18、替代字符数据查询

import pandas as pd

from sqlalchemy import create_engine

def pattern_to_sql_like(pattern):

"""

将用户输入的模式(如 1348-??4-GB-*)转换为 SQL 的 LIKE 语法。

规则:

- ?? → 替换为 __(两个下划线,匹配任意两个字符)

- * → 替换为 %(百分号,匹配任意多个字符)

"""

sql_pattern = (

pattern.replace("?", "_") # 替换 ??

.replace("*", "%") # 替换 *

)

return sql_pattern

# 用户输入的原始模式

user_pattern = "1344-??1-2?-*"

# 转换为 SQL 的 LIKE 模式

sql_like_pattern = pattern_to_sql_like(user_pattern)

# 创建数据库引擎

engine = create_engine('mysql+mysqlconnector://root:502@localhost:3306/shn')

# 动态生成 SQL 查询(替换表名和列名)

sql_query = f"""

SELECT *

FROM b

WHERE b_parentPart like '{sql_like_pattern}'

"""

# 执行查询并返回 DataFrame

with engine.connect() as conn:

df = pd.read_sql_query(sql_query, conn)

# 查看结果

print(df)

返回


b_year b_bom_version ... b_modifiedDateTime b_cease
0 2020 1344-021-2B-7.01 ... 2021-12-03 10:36:27
1 2020 1344-021-2B-7.01 ... 2021-12-03 10:36:44
.. ... ... ... ... ...
312 2020 1344-121-2B-D.02 ... 2019-06-17 13:53:20
313 2020 1344-121-2B-D.02 ... 2019-06-17 13:53:20